﻿using H.QuickDoes;
using System;
using System.Collections.Generic;
using System.Threading;

namespace H.QuickDo.QuickDoes
{
    public class HQuickDo<C> : IQuickDo<C> where C : IQDContext
    {
        ///<inheritdoc/>
        public C Context { get; }

        ///<inheritdoc/>
        public CancellationToken CT { get; set; } = CancellationToken.None;

        ///<inheritdoc/>
        public Func<int, int> FailedDelayFunc { get; set; }

        /// <summary>
        /// 内部采用的随机数对象
        /// </summary>
        private readonly Random _Random = new Random();

        /// <summary>
        /// 存储所有已经创建的Action
        /// </summary>
        private readonly Dictionary<int, QDAction<C>> _AllActions = new Dictionary<int, QDAction<C>>();

        /// <summary>
        /// 生成一个新的快速操作对象
        /// </summary>
        /// <param name="context"></param>
        public HQuickDo(C context)
        {
            Context = context;
            FailedDelayFunc = CreateWaitingInterval(500, 1000);
        }

        /// <summary>
        /// 创建一个生成随机延时的函数
        /// </summary>
        /// <param name="minDelayMs">最短延时</param>
        /// <param name="maxDelayMs">最长延时</param>
        /// <returns>返回一个延时时间产生器函数</returns>
        public Func<int, int> CreateWaitingInterval(int minDelayMs, int maxDelayMs)
        {
            return new Func<int, int>((_) =>
            {
                return _Random.Next(minDelayMs, maxDelayMs);
            });
        }

        ///<inheritdoc/>
        public void SetAction(int actionID, Func<IQuickDo<C>, dynamic> action, int retry, int? rollbackID, Func<int, int> retryDelay = null)
        {
            _AllActions[actionID] = new QDAction<C>(action ?? throw new ArgumentNullException(nameof(action)), retry, rollbackID, retryDelay);
        }

        ///<inheritdoc/>
        public bool DoAction(int id, bool enableTransfer = true)
        {
        Start:
            if (_AllActions.TryGetValue(id, out QDAction<C> action))
            {
                int retry = 0;
                while (true)
                {
                    dynamic res = action.Action(this);
                    if (res is int nextAction)
                    {
                        id = nextAction;
                        goto Start;
                    }
                    else if (res is bool result)
                    {
                        if (result)
                        {
                            return true;
                        }
                    }
                    else if (res is int[] nextActions)
                    {
                        if (nextActions.Length > 0)
                        {
                            id = nextActions[_Random.Next(nextActions.Length)];
                            goto Start;
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException("无效返回值,返回值只能为:Int,Int[],bool");
                    }
                    if (++retry <= action.Retry)
                    {
                        int? delay = (action.RetryDelay ?? FailedDelayFunc)?.Invoke(retry);
                        if (delay.HasValue)
                        {
                            Delay(delay.Value, CT);
                        }
                    }
                    else
                    {
                        if (action.RollbackID.HasValue)
                        {
                            id = action.RollbackID.Value;
                            goto Start;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }
            else
            {
                throw new InvalidOperationException($"没有找到编号为[{id}]的Action");
            }

        }

        /// <summary>
        /// 延时函数,每一秒进行一次取消任务的判断
        /// </summary>
        /// <param name="delayMs">延时的毫秒数</param>
        /// <param name="ct">取消延时的令牌</param>
        /// <returns>返回真实的延时时间(毫秒)</returns>
        protected int Delay(int delayMs, CancellationToken ct)
        {
            if (delayMs <= 0)
            {
                return 0;
            }
            DateTime start = DateTime.Now;
            DateTime end = start + TimeSpan.FromMilliseconds(delayMs);

            while ((end - DateTime.Now).TotalMilliseconds > 1000)
            {
                if (ct.IsCancellationRequested)
                {
                    return (int)(DateTime.Now - start).TotalMilliseconds;
                }
                Thread.Sleep(1000);
            }

            Thread.Sleep((int)(end - DateTime.Now).TotalMilliseconds);
            return (int)(DateTime.Now - start).TotalMilliseconds;
        }

        ///<inheritdoc/>
        public int Delay(int delayMs)
        {
            return Delay(delayMs, CT);
        }

        ///<inheritdoc/>
        public int Delay(int minDelayMs, int maxDelayMs)
        {
            return Delay(_Random.Next(minDelayMs, maxDelayMs), CT);
        }


    }
}

